<template>
	<view class="container">
		<view class="content_box">
			<view class="user_info_from">
				<view class="from_title">
					<view class="from_title_name">个人基本信息</view>
					<view class="from_title_tips">为保证审核顺利进行，请认真填写并确保信息的真实性。</view>
				</view>

				<view class="from_item">
					<view class="from_item_label"><text>*</text>真实姓名</view>
					<view class="from_item_value">
						<input type="text" v-model="userInfoFrom.userName" placeholder="输入真实姓名" maxlength="15"
							:adjust-position="false" placeholder-style="color: #CACCCC" @blur="userNameBlur"
							@confirm="userNameConfirm" />
					</view>
				</view>
				<view class="from_item">
					<view class="from_item_label"><text>*</text>身份证号 </view>
					<view class="from_item_value">
						<input type="idcard" v-model="userInfoFrom.userIdCard" placeholder="输入身份证号" maxlength="18"
							:adjust-position="false" placeholder-style="color: #CACCCC" @blur="userIdCardBlur"
							@confirm="userIdCardConfirm" />
					</view>
				</view>
				<view class="from_item">
					<view class="from_item_label"><text>*</text>年龄</view>
					<view class="from_item_value">
						<input type="number" v-model="userInfoFrom.age" placeholder="输入年龄" maxlength="3"
							:adjust-position="false" placeholder-style="color: #CACCCC" @blur="ageBlur"
							@confirm="ageConfirm" />
					</view>
				</view>
				<view class="from_item">
					<view class="from_item_label"><text>*</text>性别</view>
					<view class="from_item_value from_item_value_sex">
						<view @tap="sexBtn(0)" :class="userInfoFrom.sex === 0 ? 'from_item_value_sex_act' : '' ">女
						</view>
						<view @tap="sexBtn(1)" :class="userInfoFrom.sex === 1 ? 'from_item_value_sex_act' : '' ">男
						</view>
					</view>
				</view>
				<view class="from_item">
					<view class="from_item_label"><text>*</text>手机号</view>
					<view class="from_item_value from_item_value_phone">
						<view class="from_item_value_phone_number">{{userInfoFrom.phone}}</view>
						<view class="from_item_value_phone_btn" @tap="openRegisterPopup">更换</view>
					</view>
				</view>
				<view class="from_item">
					<view class="from_item_label"><text>*</text>微信号</view>
					<view class="from_item_value">
						<input type="text" v-model="userInfoFrom.wxPhone" placeholder="输入微信号" maxlength="20"
							:adjust-position="false" placeholder-style="color: #CACCCC" @blur="wxPhoneBlur"
							@confirm="wxPhoneConfirm" />
					</view>
				</view>
			</view>
			<view class="user_info_from">
				<view class="from_title">
					<view class="from_title_name"><text>*</text>上传本人手持身份证照片</view>
				</view>
				<view class="up_idcard">
					<image @tap="upUserIdCardImg" :class="userInfoFrom.userIdCardImg ? '' : 'up_idcard_add_icon'"
						:src="userInfoFrom.userIdCardImg ? userInfoFrom.userIdCardImg : url + 'icon-85.png'" mode="">
					</image>
					<image @tap.stop="delImg" v-if="userInfoFrom.userIdCardImg" class="del_img"
						:src="url + 'icon-100.png'" mode=""></image>
				</view>
				<view class="up_idcard_see" @tap="openExampleImg">查看示例<uni-icons type="right" size="14"></uni-icons>
				</view>
				<view class="up_idcard_tips">
					<view class="up_idcard_tips_title">注意事项：</view>
					<view class="up_idcard_tips_text">1、手持身份证置于胸前，双手手臂完整露出;不要遮挡住面部特征。</view>
					<view class="up_idcard_tips_text">2、认证人面部及身份证信息清晰可见，照片放大后，字迹清晰、无模糊。</view>
				</view>
			</view>

			<view class="bottom_btn">
				<view class="" @tap="getUserInfo">下一步</view>
			</view>
		</view>

		<uni-popup ref="popupRegisterRef" type="center" :is-mask-click="true" background-color="#fff"
			border-radius="24rpx 24rpx 24rpx 24rpx">
			<view class="register">
				<view class="register-title">绑定手机号</view>
				<uni-icons @click="popupRegisterRef.close()" class="close" type="closeempty" size="28"></uni-icons>
				<view class="register-mobile">
					<view class="code">
						<span>+86</span>
					</view>
					<input v-model="registerObj.mobile" type="number" maxlength="11" :focus="true"
						placeholder="请输入手机号" />
				</view>
				<view class="register-code">
					<input v-model="registerObj.code" type="number" maxlength="6" placeholder="请输入验证码" />
					<view class="send">
						<view v-if="!registerObj.yzmShow" @click="registerObj.sendApiCode(registerObj.time)">发送验证码
						</view>
						<view v-else style="color: #7C807F;">{{registerObj.time}}s 秒</view>
					</view>
				</view>
				<view @tap="register" class="xjs-btn-primary">确定</view>
			</view>
		</uni-popup>
		<uni-popup ref="popupExampleImgRef" type="center" :is-mask-click="false" background-color="#fff"
			border-radius="24rpx 24rpx 24rpx 24rpx">
			<view class="register example">
				<view class="register-title">手持身份证示例</view>
				<uni-icons @click="popupExampleImgRef.close()" class="close" type="closeempty" size="28"></uni-icons>
				<image :src="url + 'sfz.png'" mode=""></image>
			</view>
		</uni-popup>

	</view>
</template>

<script lang="ts" setup>
	import { reactive, onMounted, computed, defineProps, ref } from 'vue'
	import config from '@/config/index'
	import api from '@/api'
	import { useUserStoreToRefs } from '@/store/useUserStore'

	const { userInfo, access_token } = useUserStoreToRefs()
	const emit = defineEmits(['confirm'])
	const userInfoFrom = reactive<{
		userName ?: string
		userIdCard ?: number | string
		age ?: string | number
		sex ?: string | number
		phone ?: string | number
		wxPhone ?: string | number
		userIdCardImg ?: string
	}>({
		userName: '',
		userIdCard: '',
		age: '',
		sex: '',
		phone: userInfo.value.phone,
		wxPhone: '',
		userIdCardImg: ''
	})
	const url = ref('https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/')  //图片前缀
	const popupRegisterRef = ref()
	const popupExampleImgRef = ref()
	const props = defineProps({
		userInfoFrom: {
			type: Object,
			default: {}
		}

	})
	
	onMounted(() => {
		userInfoFrom.age = 3
	})
	const registerObj = reactive<any>({
		mobile: "",
		code: "",
		time: 60,
		yzmShow: false,
		ttuserInfo: {},
		sendApiCode: async () => {
			if (!parseInt(registerObj.mobile)) {
				uni.showToast({
					title: '请输入11位手机号码',
					icon: 'none'
				});
				return false
			}
			let mobileReg = /^1[3456789]\d{9}$/
			if (!mobileReg.test(registerObj.mobile)) {
				uni.showToast({
					title: '手机号格式有误',
					icon: 'none'
				});
				return false
			}
			const res : any = await api({
				method: 'get',
				url: `/mobile/code/v2?mobile=${registerObj.mobile}&type=register&countryCode=86&isVoiceCode=0&sourceType=1`
			})
			if (res.code !== 0) {
				uni.showToast({
					icon: 'none',
					mask: true,
					title: res.msg
				})
			} else {
				uni.showToast({
					icon: 'none',
					mask: true,
					title: "验证码已发送，请注意查收"
				})
				registerObj.sendCode(registerObj.time)
			}
		},
		sendCode: (num) => {
			registerObj.yzmShow = true
			setTimeout(() => {
				if (registerObj.time <= 0) {
					registerObj.yzmShow = false
					registerObj.time = 60
					return
				} else {
					registerObj.time--
					registerObj.sendCode(num)
				}
			}, 1000)
		}
	})
	const isUserNameCheck = ref(false)

	const openRegisterPopup = () => {
		console.log(1)
		popupRegisterRef.value.open()
	}
	const register = async () => {
		if (!parseInt(registerObj.mobile)) {
			uni.showToast({
				title: '请输入11位手机号码',
				icon: 'none'
			});
			return false
		}
		let mobileReg = /^1[3456789]\d{9}$/
		if (!mobileReg.test(registerObj.mobile)) {
			uni.showToast({
				title: '手机号格式有误',
				icon: 'none'
			});
			return false
		}
		if (registerObj.mobile == userInfoFrom.phone) {
			uni.showToast({
				title: '请输入不同的手机号',
				icon: 'none'
			});
			return false
		}
		if (registerObj.code.trim().length <= 0) {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: "请输入6位数验证码"
			})
			return
		}
		const res : any = await api({
			method: 'post',
			url: `/mall/user/v2/checkVerificationCode`,
			data: {
				code: registerObj.code,
				mobile: registerObj.mobile,
				countryCode: "86",
			}
		})
		if (res.data == true) {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: "更换成功！"
			})
			userInfoFrom.phone = registerObj.mobile
			popupRegisterRef.value.close()
			registerObj.code = ''
			registerObj.mobile = ''
		} else {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: res.msg
			})
		}
	}
	const openExampleImg = () => {
		popupExampleImgRef.value.open()
	}
	const userNameConfirm = ({ detail: { value } } : any) => {
		userInfoFrom.userName = value
	}
	const userNameBlur = ({ detail: { value } } : any) => {
		userInfoFrom.userName = value
	}
	const userIdCardConfirm = ({ detail: { value } } : any) => {
		userInfoFrom.userIdCard = value
		getIdCardInfo(userInfoFrom.userIdCard)
	}
	const userIdCardBlur = ({ detail: { value } } : any) => {
		userInfoFrom.userIdCard = value
		getIdCardInfo(userInfoFrom.userIdCard)
	}
	const isValidChineseID = (id) => { //身份证校验
		if (!/^\d{18}$/.test(id)) {
			return false;
		}
		const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
		let sum = 0;
		for (let i = 0; i < 17; i++) {
			sum += parseInt(id[i], 10) * weights[i];
		}
		const mod = sum % 11;
		return checkCode[mod] === id[17].toUpperCase();
	}
	const getIdCardInfo = (id) => {
		if (!isValidChineseID(userInfoFrom.userIdCard)) {
			return null;
		}
		userInfoFrom.sex = parseInt(id[16], 10) % 2 === 0 ? 0 : 1; // 根据性别码的最后一位奇偶判断性别
		var myDate = new Date();
		var month = myDate.getMonth() + 1;
		var day = myDate.getDate();
		var age = myDate.getFullYear() - id.substring(6, 10) - 1;
		if (id.substring(10, 12) < month || id.substring(10, 12) == month && id.substring(12, 14) <= day) {
			age++;
		}
		userInfoFrom.age = age
	}
	const ageConfirm = ({ detail: { value } } : any) => {
		userInfoFrom.age = value
	}
	const ageBlur = ({ detail: { value } } : any) => {
		userInfoFrom.age = value

	}
	const sexBtn = (value) => {
		userInfoFrom.sex = value
	}
	const wxPhoneConfirm = ({ detail: { value } } : any) => {
		userInfoFrom.wxPhone = value
	}
	const wxPhoneBlur = ({ detail: { value } } : any) => {
		userInfoFrom.wxPhone = value
	}

	const upUserIdCardImg = () => {
		if (userInfoFrom.userIdCardImg) {
			let images = [userInfoFrom.userIdCardImg]
			uni.previewImage({
				current: 0,
				urls: images,
			});
		} else {
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ["camera", "album"], //从相册选择
				success: function (res) {
					uploadImage(res.tempFilePaths[0])
				}
			})
		}

	}
	const uploadImage = (filePath) => {
		uni.uploadFile({
			url: config.api + '/api/mall/studio/apply-studio-record/uploadCoverPic',
			filePath: filePath,
			name: 'file',
			header: {
				'Authorization': access_token.value ? 'Bearer ' + access_token.value :
					'Basic bWFsbC1hcHA6bWFsbC1hcHA=',
				'x-flow-id': new Date().getTime(),
				"x-client-id": ""
			},
			success: async (uploadFileRes) => {
				userInfoFrom.userIdCardImg = JSON.parse((uploadFileRes.data)).data
			},
			fail: (error) => {
				console.error(error);
			}
		})
	}

	const delImg = () => {
		uni.showModal({
			title: '确定要删除吗',
			success: async (res) => {
				if (res.confirm) {
					userInfoFrom.userIdCardImg = ''
				} else if (res.cancel) {

				}
			}
		})
	}
	const userNameCheck = async () => {

		const res : any = await api({
			method: 'POST',
			url: `/mall/studio/apply-studio-record/checkIdCard?name=${userInfoFrom.userName}&cardNumber=${userInfoFrom.userIdCard}`

		})
		if (res) {
			isUserNameCheck.value = res.data
			console.log(isUserNameCheck.value)
		}
	}

	const getUserInfo = async () => {
		await userNameCheck()
		console.log(userInfo.value.phone)
		if (!userInfoFrom.userName) {
			return toastfnc('请输入真实姓名')
		}
		if (!userInfoFrom.userIdCard) {
			return toastfnc('请输入身份证号')
		}
		if (!userInfoFrom.age) {
			return toastfnc('请输入年龄')
		}
		if (Number(userInfoFrom.sex) < 0) {
			return toastfnc('请选择性别')
		}
		if (!userInfoFrom.wxPhone) {
			return toastfnc('请输入微信号')
		}
		if (!isUserNameCheck.value) {
			return toastfnc('身份证号与姓名不匹配')
		}
		if (!userInfoFrom.userIdCardImg) {
			return toastfnc('请上传本人手持身份证照')
		}
		emit('confirm', userInfoFrom)
	}
	const toastfnc = (tipsText : string) => {
		uni.showToast({
			title: tipsText,
			icon: 'none'
		})

	}
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: calc(var(--safe-area-bottom) + 104rpx);
	}

	.user_info_from {
		padding: 48rpx 32rpx;
		margin-top: 24rpx;
		background-color: #fff;
		border-radius: 24rpx;
		box-sizing: border-box;
		line-height: 1;

		.from_title {

			.from_title_name {
				margin-bottom: 16rpx;
				font-size: 36rpx;
				color: #1B2120;
				font-weight: bold;

				text {
					color: #FF6084;
				}
			}

			.from_title_tips {
				font-size: 24rpx;
				color: #7C807F;
			}
		}

		.from_item {
			margin-top: 64rpx;
			display: flex;
			justify-content: space-between;
			font-size: 30rpx;
			line-height: 1;

			.from_item_label {
				width: 138rpx;
				color: #1B2120;
				font-weight: bold;

				text {
					color: #FF6084;
				}
			}

			.from_item_value {
				padding-bottom: 24rpx;
				width: 460rpx;
				border-bottom: 2rpx solid #E4E6E6;
				color: #7C807F;

				input {
					margin-top: -14rpx;
					line-height: 1;
				}
			}

			.from_item_value_phone {
				display: flex;
				justify-content: space-between;

				.from_item_value_phone_number {}

				.from_item_value_phone_btn {
					color: #FF6084;
				}
			}

			.from_item_value_sex {
				display: flex;
				align-items: center;

				view {
					margin-right: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 120rpx;
					height: 70rpx;
					box-sizing: border-box;
					border: 1rpx solid #CACCCC;
					background-color: #fff;
					border-radius: 200rpx;
				}

				.from_item_value_sex_act {
					border: 1rpx solid #FF6084;
					color: #FF6084;
				}
			}


		}


		.up_idcard {
			width: 622rpx;
			height: 394rpx;
			background-color: #F9F6F6;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			image {
				width: 622rpx;
				height: 394rpx;
			}

			.del_img {
				position: absolute;
				right: 8rpx;
				top: 8rpx;
				width: 32rpx;
				height: 30rpx;
			}

			.up_idcard_add_icon {
				width: 120rpx;
				height: 120rpx;
			}
		}

		.up_idcard_see {
			margin: 18rpx 0 64rpx 0;
			text-align: center;
			font-size: 28rpx;
			color: #1B2120;
			font-weight: bold;

		}

		.up_idcard_tips {
			font-size: 24rpx;
			color: #7C807F;

			.up_idcard_tips_title {
				margin-bottom: 18rpx;
				font-weight: bold;
			}

			.up_idcard_tips_text {
				line-height: 1.4;
			}
		}
	}

	.bottom_btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding-bottom: calc(var(--safe-area-bottom));
		line-height: 1;

		view {
			width: 622rpx;
			margin: 8rpx auto;
			padding: 30rpx;
			background: linear-gradient(90deg, #FF6188 0%, #FF5252 100%);
			font-size: 28rpx;
			color: #FFFFFF;
			border-radius: 62rpx;
			text-align: center;
		}
	}

	.register {
		// padding: 0 40rpx calc(var(--safe-area-bottom) + 5rpx);
		padding: 0 40rpx 60rpx;
		box-sizing: border-box;
		position: relative;
		width: 686rpx;

		image {
			width: 220rpx;
			height: 220rpx;
		}

		&-title {
			text-align: center;
			font-weight: bold;
			padding: 40rpx 0 80rpx;
		}

		.close {
			position: absolute;
			top: 40rpx;
			right: 40rpx;
		}

		&-mobile {
			height: 128rpx;
			border-radius: 32rpx;
			background-color: #F5F6F7;
			display: flex;
			align-items: center;
			padding: 32rpx;
			box-sizing: border-box;
			margin-bottom: 32rpx;

			.code {
				display: flex;
				justify-content: center;
				align-items: center;
			}

			>input {
				font-size: 32rpx;
				margin-left: 32rpx;
			}
		}

		&-code {
			height: 128rpx;
			border-radius: 32rpx;
			background-color: #F5F6F7;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 32rpx;
			box-sizing: border-box;
			margin-bottom: 80rpx;

			>input {
				font-size: 32rpx;
				margin-left: 32rpx;
				width: 300rpx;
			}

			.send {
				font-size: 26rpx;
				color: var(--color-primary);
				width: 180rpx;
				text-align: center;
				border-left: 1px solid #7C807F;
			}
		}
	}
</style>